package ch.zbw.timeline.service;

import java.util.List;

import ch.zbw.timeline.domain.Allocation;
import ch.zbw.timeline.domain.DailyPresence;
import ch.zbw.timeline.domain.Entry;
import ch.zbw.timeline.domain.OverTimePool;
import ch.zbw.timeline.repository.AllocationRepository;
import ch.zbw.timeline.repository.EntryRepository;
import ch.zbw.timeline.repository.hibernate.HibernateAllocationRepository;
import ch.zbw.timeline.repository.hibernate.HibernateEntryRepository;

/**
 * Class that implements the Entry-Interface to handle the Entry
 * 
 * @author Andreas Kaderli
 * @version 15.12.2011
 * 
 */
public class ZbwEntryService implements EntryService {

	private AllocationRepository allocationRepository = new HibernateAllocationRepository();
	private EntryRepository entryRepository = new HibernateEntryRepository();

	// private EntryRepository entryRepository = new MockEntryRepository();
	// private AllocationRepository allocationRepository = new MockAllocationRepository();

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * ch.zbw.timeline.service.EntryService#createEntry(ch.zbw.timeline.domain
	 * .DailyPresence, double, ch.zbw.timeline.domain.Allocation,
	 * java.lang.String, ch.zbw.timeline.domain.OverTimePool)
	 */
	@Override
	public Entry createEntry(DailyPresence dailyPresence, double duration,
			Allocation allocation, String comment, OverTimePool overTimePool) {
		Entry entry = new Entry();

		entry.setDailyPresenceFk(dailyPresence.getId());
		entry.setDuration(duration);
		entry.setAllocationFk(allocation.getId());
		entry.setComment(comment);
		if (overTimePool != null) {
			entry.setOvertimePoolFk(overTimePool.getId());
		}
		entry.setAllocation(allocation);

		Entry ent = entryRepository.saveEntry(entry);
		return ent;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * ch.zbw.timeline.service.EntryService#saveEntry(ch.zbw.timeline.domain
	 * .Entry)
	 */
	@Override
	public Entry saveEntry(Entry entry) {
		if (entry != null) {
			return entryRepository.saveEntry(entry);
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * ch.zbw.timeline.service.EntryService#getAllEntries(ch.zbw.timeline.domain
	 * .DailyPresence)
	 */
	@Override
	public List<Entry> getAllEntries(DailyPresence dailyPresence) {
		if (dailyPresence != null) {

			List<Entry> list = entryRepository.getAllEntries(dailyPresence
					.getId());

			for (int i = 0; i < list.size(); i++) {
				Entry entry = list.get(i);
				int allocationFk = entry.getAllocationFk();
				Allocation allocation = allocationRepository
						.getAllocationById(allocationFk);

				entry.setAllocation(allocation);
			}
			return list;
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * ch.zbw.timeline.service.EntryService#delete(ch.zbw.timeline.domain.Entry)
	 */
	@Override
	public void delete(Entry entry) {
		entryRepository.delete(entry);
	}
}
